//
//  TRBuyCarViewController.m
//  WeiMiLan
//
//  Created by anan on 15/8/3.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "TRAddressListViewController.h"

@interface TRAddressListViewController ()
{
    MJRefreshHeaderView *refreshHeaderView;
    MJRefreshFooterView *refreshFooterView;
}
@end

@implementation TRAddressListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.contents = [[NSMutableArray alloc] init];
    [self initNavigation];
    
    UINib *nib1 = [UINib nibWithNibName:@"TRAddressTableViewCell" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"TRAddressTableViewCell"];
    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self addHeader];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [refreshHeaderView beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refresh {
    [refreshHeaderView beginRefreshing];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"所有收货地址";
    
    [self.weChatNavigationBar.leftButton setImage:[UIImage imageNamed:@"button_nav_back_a"] forState:UIControlStateNormal];
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(buttonBackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.weChatNavigationBar.rightButton.hidden = NO;
    [self.weChatNavigationBar.rightButton setTitle:@"添加" forState:UIControlStateNormal];
    self.weChatNavigationBar.rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.weChatNavigationBar.rightButton sizeToFit];
    [self.weChatNavigationBar.rightButton setImage:nil forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(buttonAddAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonAddAction:(UIButton*)button {
    TRAddressEditViewController *vc = [[TRAddressEditViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)buttonBackAction:(UIButton*)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadData {
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/UserAddress?type=14001&userId=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = resultDic[@"USER_INFO_RSP"][@"ADDRESS"];
        [self.contents removeAllObjects];
        [self.contents addObjectsFromArray:arr];
        
        if (self.contents.count==0) {
            [SVProgressHUD showErrorWithStatus:@"收货地址为空"];
        }
        
        [self endRefresh];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    long count = self.contents==nil?0:self.contents.count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRAddressTableViewCell"];
    if (cell == nil) {
        cell = [[TRAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRAddressTableViewCell"];
    }
    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    cell.buttonOk.hidden = YES;
    [cell setNeedsDisplay];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRAddressTableViewCell"];
    if (cell == nil) {
        cell = [[TRAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRAddressTableViewCell"];
    }
    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    return [cell getHeight];
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    UIActionSheet *sheet = nil;
    if (self.delegate) {
        sheet = [[UIActionSheet alloc] initWithTitle:@"..." delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"选择",@"设为默认地址",@"编辑",@"删除", nil];
    }else{
        sheet = [[UIActionSheet alloc] initWithTitle:@"..." delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"设为默认地址",@"编辑",@"删除", nil];
    }
    sheet.tag = indexPath.row;
    [sheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSDictionary *dic = [self.contents objectAtIndex:actionSheet.tag];
    if (self.delegate==nil) {
        buttonIndex = buttonIndex+1;
    }
    switch (buttonIndex) {
        case 0:
        {
            if (self.delegate) {
                [self.delegate onAddressSelectWithInfo:dic];
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 1:
        {
            [self setDefaultAdderssWithInfo:dic];
        }
            break;
        case 2:
        {
            TRAddressEditViewController *vc = [[TRAddressEditViewController alloc] init];
            vc.adderssDic = dic;
            [self presentViewController:vc animated:YES completion:nil];
        }
            break;
        case 3:
        {
            [self deleteAdderssWithInfo:dic];
        }
            break;
            
        default:
            break;
    }
}

- (void)deleteAdderssWithInfo:(NSDictionary*)info {
    [QLMaskUtil showMaskLoadingWithView:self.view];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/UserAddress?type=14004&userId=%@&id=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,info[@"ID"]];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        [refreshHeaderView beginRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];

}

- (void)setDefaultAdderssWithInfo:(NSDictionary*)info {
    [QLMaskUtil showMaskLoadingWithView:self.view];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/UserAddress?type=14005&userId=%@&id=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,info[@"ID"]];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        [refreshHeaderView beginRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
    
}

- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    refreshHeaderView = header;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadData];
    };
}

- (void)endRefresh
{
    // 刷新表格
    [self.tableView reloadData];
    [refreshFooterView endRefreshing];
    [refreshHeaderView endRefreshing];
}

@end
